package com.qiaofang.applet.rest;

import com.qiaofang.applet.common.context.QfContextHolder;
import com.qiaofang.applet.common.dto.DataRequest;
import com.qiaofang.applet.common.dto.DataResponse;
import com.qiaofang.applet.common.dto.PageDataRequest;
import com.qiaofang.applet.common.util.BaiduMapUtil;
import com.qiaofang.applet.common.util.PageUtil;
import com.qiaofang.applet.constants.UpDownFlagConstants;
import com.qiaofang.applet.service.member.domain.Employee;
import com.qiaofang.applet.service.member.service.EmployeeService;
import com.qiaofang.applet.service.member.service.dto.EmployeeListDto;
import com.qiaofang.applet.service.member.service.dto.EmployeeQueryDto;
import com.qiaofang.applet.service.other.domain.CityCompany;
import com.qiaofang.applet.service.other.domain.Corporation;
import com.qiaofang.applet.service.other.service.CarouselService;
import com.qiaofang.applet.service.other.service.CityCompanyService;
import com.qiaofang.applet.service.other.service.CorporationService;
import com.qiaofang.applet.service.other.service.DictCorpService;
import com.qiaofang.applet.service.other.service.dto.*;
import com.qiaofang.applet.service.property.domain.FirsthandEstate;
import com.qiaofang.applet.service.property.domain.Property;
import com.qiaofang.applet.service.property.service.FirsthandEstateService;
import com.qiaofang.applet.service.property.service.PropertyService;
import com.qiaofang.applet.service.property.service.dto.*;
import com.qiaofang.applet.service.property.service.mapstruct.FirsthandEstateMapper;
import com.qiaofang.applet.service.property.service.mapstruct.PropertyMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author daiyuxaing
 */
@Slf4j
@RestController
@RequestMapping("/api/web/main")
@Api(tags = "首页：首页模块")
public class MainController {

    @Autowired
    private PropertyService propertyService;

    @Autowired
    private FirsthandEstateService firsthandEstateService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private CarouselService carouselService;

    @Autowired
    private CorporationService corporationService;

    @Autowired
    private DictCorpService dictCorpService;

    @Autowired
    private PropertyMapper propertyMapper;

    @Autowired
    private FirsthandEstateMapper firsthandEstateMapper;

    @Autowired
    private CityCompanyService cityCompanyService;

    @PostMapping(value = "/searchCarousel")
    @ApiOperation(value = "查询轮播图", notes = "查询轮播图")
    public DataResponse<List<CarouselResponseDto>> searchCarousel(@RequestBody @Valid DataRequest<CityQueryDto> request) {
        CarouselQueryDto queryDto = new CarouselQueryDto();
        queryDto.setCorporationCode(QfContextHolder.getContext().getCorporationCode());
        queryDto.setCarouselType("移动端");
        queryDto.setCarouselStatus("上架");
        queryDto.setCityCode(request.getParam().getCityCode());
        return DataResponse.ok(carouselService.getList(queryDto));
    }

    @PostMapping("/searchHotFirsthand")
    @ApiOperation(value = "查询新房推荐列表", notes = "查询新房推荐列表")
    public DataResponse<Page<FirsthandEstateListDto>> searchHotFirsthand(@RequestBody @Valid PageDataRequest<CityQueryDto> request) {
        FirsthandEstateQueryDto queryDto = new FirsthandEstateQueryDto();
        queryDto.setRecommend(true);
        queryDto.setCityCode(request.getParam().getCityCode());
        queryDto.setUpDownFlag(UpDownFlagConstants.UP_FLAG.getValue());

        Page<FirsthandEstate> firsthandEstatePage = firsthandEstateService.findAllHotFirsthandByParams(queryDto, PageUtil.getPageable(request));

        Page<FirsthandEstateListDto> result = firsthandEstateMapper.convertDomainToListDto(firsthandEstatePage);

        return DataResponse.ok(result);
    }

    @PostMapping("/searchHotSale")
    @ApiOperation(value = "查询二手房推荐列表", notes = "查询二手房推荐列表")
    public DataResponse<Object> searchHotSale(@RequestBody @Valid PageDataRequest<CityQueryDto> request) {
        SalePropertyQueryDto queryDto = new SalePropertyQueryDto();
        queryDto.setRecommend(true);
        queryDto.setCityCode(request.getParam().getCityCode());
        queryDto.setUpDownFlag(UpDownFlagConstants.UP_FLAG.getValue());

        Page<Property> propertyPage = propertyService.findAllHotSaleByParams(queryDto, PageUtil.getPageable(request));

        Page<SalePropertyListDto> result = propertyMapper.convertDomainToSaleListDto(propertyPage);

        return DataResponse.ok(result);
    }

    @PostMapping("/searchHotRent")
    @ApiOperation(value = "查询租房推荐列表", notes = "查询租房推荐列表")
    public DataResponse<Page<RentPropertyListDto>> searchHotRent(@RequestBody @Valid PageDataRequest<CityQueryDto> request) {
        RentPropertyQueryDto queryDto = new RentPropertyQueryDto();
        queryDto.setRecommend(true);
        queryDto.setCityCode(request.getParam().getCityCode());
        queryDto.setUpDownFlag(UpDownFlagConstants.UP_FLAG.getValue());

        Page<Property> propertyPage = propertyService.findAllHotRentByParams(queryDto, PageUtil.getPageable(request));

        Page<RentPropertyListDto> result = propertyMapper.convertDomainToRentListDto(propertyPage);

        return DataResponse.ok(result);
    }

    @PostMapping("/searchHotEmployee")
    @ApiOperation(value = "查询经纪人推荐列表", notes = "查询经纪人推荐列表")
    public DataResponse<Page<EmployeeListDto>> searchHotEmployee(@RequestBody @Valid PageDataRequest<CityQueryDto> request) {
        EmployeeQueryDto queryDto = new EmployeeQueryDto();
        queryDto.setRecommend(true);
        queryDto.setCityCode(request.getParam().getCityCode());
        queryDto.setCorporationCode(QfContextHolder.getContext().getCorporationCode());

        Page<Employee> employeePage = employeeService.findAllByParams(queryDto, PageUtil.getPageable(request));

        Page<EmployeeListDto> result = employeeService.convertDomainToListDto(employeePage, QfContextHolder.getContext().getCorporationCode());

        return DataResponse.ok(result);
    }

    @PostMapping("getHtmlConfigFunction")
    @ApiOperation(value = "首页功能展示模块", notes = "首页功能展示模块")
    public DataResponse<Object> getHtmlConfigFunction() {
        String corporationCode = QfContextHolder.getContext().getCorporationCode();
        Corporation corporation = corporationService.getCorporationByCorporationCode(corporationCode);

        CityCompany cityCompany = cityCompanyService.getDefaultCityCompany(corporationCode);

        HtmlConfigFunctionDto dto = HtmlConfigFunctionDto
                .builder()
                .appId(corporation.getAuthAppId())
                .code(cityCompany.getCityCode()) //cityCoe 默认城市Code
                .name(cityCompany.getCompanyCity()) //cityName 默认城市名称
                .homeLogo(corporation.getHomeLogo())
                .logo(corporation.getLogo())
                .miniName(corporation.getMiniName())
                .navigationBarTitle(corporation.getNavigationBarTitle())
                .companyUuid(cityCompany.getCompanyUuid())
                .universeCityId(cityCompany.getUniverseCityId())
                .build();
        return DataResponse.ok(dto);
    }

    /**
     * 获取首页宫格配置顺序list
     */
    @PostMapping(value = "/listTool")
    @ApiOperation(value = "获取首页宫格配置顺序list", notes = "获取首页宫格配置顺序list")
    @Deprecated
    public DataResponse<List<ToolDto>> listTool(@RequestBody DataRequest<CityQueryDto> request) {
        List<DictDto> list = dictCorpService.getToolList();
        List<ToolDto> dtoList = new ArrayList<>(list.size());
        if (CollectionUtils.isEmpty(list)) {
            return DataResponse.ok(dtoList);
        }
        for (DictDto dictDto : list) {
            ToolDto toolDto = new ToolDto();
            toolDto.setToolLabel(dictDto.getDictValue());
            switch (dictDto.getDictCode()) {
                case "box_util_001":
                    toolDto.setToolPhotoUrl("index-icon-xf.png");
                    toolDto.setToolUrl("/pages/newhouse/main");
                    break;
                case "box_util_002":
                    toolDto.setToolPhotoUrl("index-icon-esf.png");
                    toolDto.setToolUrl("/pages/ershoufang/main");
                    break;
                case "box_util_003":
                    toolDto.setToolPhotoUrl("index-icon-zf.png");
                    toolDto.setToolUrl("/pages/zufang/main");
                    break;
                case "box_util_004":
                    toolDto.setToolPhotoUrl("index-icon-zxq.png");
                    toolDto.setToolUrl("/pages/community/main");
                    break;
                case "box_util_005":
                    CityCompany cityCompany = cityCompanyService.getCompanyByCityAndCorp(request.getParam().getCityCode(), QfContextHolder.getContext().getCorporationCode());
                    String txh5Url = "";
                    if (cityCompany != null && StringUtils.isNotBlank(cityCompany.getTxh5Url())) {
                        txh5Url = cityCompany.getTxh5Url();
                    }

                    try {
                        toolDto.setToolUrl("/pages/ershoufang/linkweb/main?url=" + URLDecoder.decode(txh5Url, "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                    }
                    toolDto.setToolPhotoUrl("index-icon-ccj.png");
                    break;
                case "box_util_006":
                    toolDto.setToolPhotoUrl("index-icon-wsyz.png");
                    toolDto.setToolUrl("#");
                    break;
                case "box_util_007":
                    toolDto.setToolPhotoUrl("index-icon-fdjs.png");
                    toolDto.setToolUrl("/pages/housecalc/main");
                    break;
                case "box_util_008":
                    toolDto.setToolPhotoUrl("index-icon-sfjs.png");
                    toolDto.setToolUrl("/pages/housecalc/taxation/main");
                    break;
            }
            if (StringUtils.isNotEmpty(toolDto.getToolPhotoUrl())) {
                dtoList.add(toolDto);
            }
        }
        return DataResponse.ok(dtoList);
    }

    /**
     * 获取首页宫格配置顺序list
     */
    @PostMapping(value = "/listToolV2")
    @ApiOperation(value = "获取首页宫格配置顺序list", notes = "获取首页宫格配置顺序list")
    public DataResponse<List<ToolDto>> listToolV2(@RequestBody DataRequest<CityQueryDto> request) {
        List<DictDto> list = dictCorpService.getToolList();
        List<ToolDto> dtoList = new ArrayList<>(list.size());
        if (CollectionUtils.isEmpty(list)) {
            return DataResponse.ok(dtoList);
        }
        for (DictDto dictDto : list) {
            ToolDto toolDto = new ToolDto();
            toolDto.setToolLabel(dictDto.getDictValue());
            switch (dictDto.getDictCode()) {
                case "box_util_001":
                    toolDto.setToolPhotoUrl(dictDto.getDictImg());
                    toolDto.setToolUrl("/pages/newhouse/main");
                    break;
                case "box_util_002":
                    toolDto.setToolPhotoUrl(dictDto.getDictImg());
                    toolDto.setToolUrl("/pages/ershoufang/main");
                    break;
                case "box_util_003":
                    toolDto.setToolPhotoUrl(dictDto.getDictImg());
                    toolDto.setToolUrl("/pages/zufang/main");
                    break;
                case "box_util_004":
                    toolDto.setToolPhotoUrl(dictDto.getDictImg());
                    toolDto.setToolUrl("/pages/community/main");
                    break;
                case "box_util_005":
                    CityCompany cityCompany = cityCompanyService.getCompanyByCityAndCorp(request.getParam().getCityCode(), QfContextHolder.getContext().getCorporationCode());
                    String txh5Url = "";
                    if (cityCompany != null && StringUtils.isNotBlank(cityCompany.getTxh5Url())) {
                        txh5Url = cityCompany.getTxh5Url();
                    }

                    try {
                        toolDto.setToolUrl("/pages/ershoufang/linkweb/main?url=" + URLDecoder.decode(txh5Url, "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                    }
                    toolDto.setToolPhotoUrl(dictDto.getDictImg());
                    break;
                case "box_util_006":
                    toolDto.setToolPhotoUrl(dictDto.getDictImg());
                    toolDto.setToolUrl("#");
                    break;
                case "box_util_007":
                    toolDto.setToolPhotoUrl(dictDto.getDictImg());
                    toolDto.setToolUrl("/pages/housecalc/main");
                    break;
                case "box_util_008":
                    toolDto.setToolPhotoUrl(dictDto.getDictImg());
                    toolDto.setToolUrl("/pages/housecalc/taxation/main");
                    break;
                case "box_util_009":
                    toolDto.setToolPhotoUrl(dictDto.getDictImg());
                    toolDto.setToolUrl("/pages/findAdviser/main");
                    break;
            }
            if (StringUtils.isNotEmpty(toolDto.getToolPhotoUrl())) {
                dtoList.add(toolDto);
            }
        }
        return DataResponse.ok(dtoList);
    }

    @PostMapping(value = "getCityNameByLatAndlng")
    @ApiOperation(value = "根据经纬度获取城市名称", notes = "根据经纬度获取城市名称")
    public DataResponse<String> getCityNameByLatAndlng(@RequestBody @Valid LatAndLngRequestDto latAndLngRequestDto) {
        String cityName = BaiduMapUtil.getCityByLocation(latAndLngRequestDto.getLat(), latAndLngRequestDto.getLng());

        return DataResponse.ok(cityName);
    }


    @PostMapping("/getCorporationInfo")
    @ApiOperation(value = "PC官网获取集团信息", notes = "PC官网获取集团信息")
    public DataResponse<CorporationPcInfoDto> getCorporationInfo() {
        String corporationCode = QfContextHolder.getContext().getCorporationCode();
        Corporation corporation = corporationService.getCorporationByCorporationCode(corporationCode);
        CorporationPcInfoDto dto = CorporationPcInfoDto
                .builder()
                .qrCode(corporation.getQrCode())
                .pcWebImg(corporation.getPcWebImg())
                .pcWebLogo(corporation.getPcWebLogo())
                .archivalInfo(corporation.getArchivalInfo())
                .archivalNo(corporation.getArchivalNo())
                .archivalNoUrl(corporation.getArchivalNoUrl())
                .corporationCode(corporation.getCorporationCode())
                .build();
        return DataResponse.ok(dto);
    }

    @PostMapping("/getCompanyIntroduction")
    @ApiOperation(value = "获取公司介绍", notes = "获取公司介绍")
    public DataResponse<CompanyIntroductionDto> getCompanyIntroduction(@RequestBody DataRequest<CityQueryDto> request) {
        CityCompany company = cityCompanyService.getCompanyByCityAndCorp(request.getParam().getCityCode(), QfContextHolder.getContext().getCorporationCode());
        return DataResponse.ok(CompanyIntroductionDto.builder()
                .companyName(company.getCompanyName())
                .companyLogoImg(company.getCompanyLogoImg())
                .introduction(company.getIntroduction())
                .slogan(company.getSlogan())
                .build());
    }

    /**
     * 获取首页宫格配置顺序list
     */
    @PostMapping(value = "/getSlideShowSize")
    @ApiOperation(value = "获取轮播图版本", notes = "获取轮播图版本")
    public DataResponse<String> getSlideShowSize() {
        List<DictDto> list = dictCorpService.getSlideShow();
        if (CollectionUtils.isEmpty(list) || StringUtils.isEmpty(list.get(0).getDictValue())) {
            return DataResponse.ok("小版本");
        }
        return DataResponse.ok(list.get(0).getDictValue());
    }

    @PostMapping(value = "/getIndexUIStyle")
    @ApiOperation(value = "获取小程序首页展示数据", notes = "获取小程序首页展示数据")
    public DataResponse<Map<String, List<DictDto>>> getIndexUIStyle() {
        Map<String, List<DictDto>> dictCollectionMap = dictCorpService.getDictCollectionByCorporationCode(QfContextHolder.getContext().getCorporationCode());
        return DataResponse.ok(dictCollectionMap);
    }
}
